package com.hup.utils.commons.db;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Date;

/**
 * @author hugan
 * @date 2019/8/10
 */
public class DbUtil {

    /**
     * @param index 起始于1
     */
    public static void prepared(PreparedStatement ps, int index, Object val) throws SQLException {
        //可以参考com.mysql.cj.AbstractQueryBindings.setObject(int, java.lang.Object)
        if(val == null) {
            ps.setNull(index, Types.NULL);
        } else if(val instanceof Boolean) {
            ps.setBoolean(index, (boolean) val);
        } else if(val instanceof Byte) {
            /*
            byte, char
            https://blog.csdn.net/xcy1193068639/article/details/83020266
             */
            ps.setByte(index, (byte) val);
        } else if(val instanceof Character) {
            ps.setString(index, String.valueOf((char) val));
        } else if(val instanceof Short) {
            ps.setShort(index, (short) val);
        } else if(val instanceof Integer) {
            ps.setInt(index, (int) val);
        } else if(val instanceof Long) {
            ps.setLong(index, (long) val);
        } else if(val instanceof Float) {
            ps.setFloat(index, (float) val);
        } else if(val instanceof Double) {
            ps.setDouble(index, (double) val);
        } else if(val instanceof String) {
            ps.setString(index, (String) val);
        } else if(val instanceof Date) {
            ps.setTimestamp(index, new Timestamp(((Date) val).getTime()));
        } else {
            throw new IllegalArgumentException("未定义类型:" + val.getClass());
        }
    }
}
